define([
    "underscore",
    "backbone",
    "common",
], function (_, Backbone, common) {
    'use strict';

    $(document).ajaxSend(function () {
        console.log("[ajax document] ajaxSend:" + this.lastModified);
    });
    $(document).ajaxStart(function () {
        common.ready.show();
        console.log("[ajax document] ajaxStart:" + this.lastModified);
    });
    $(document).ajaxStop(function () {
        common.ready.hide();
        console.log("[ajax document] ajaxStop:" + this.lastModified);
    });
    $(document).ajaxSuccess(function (e, xhr, options) {
        //console.log("[ajax document] ajaxSuccess:" + this.lastModified);
        console.log("ajaxSuccess:" + options.url + " | readyState:" + xhr.readyState + " | status:" + xhr.status + " | statusText:" + xhr.statusText);
    });
    $(document).ajaxError(function (event, xhr, setting, error) {
        //console.log("[ajax document] ajaxError:" + this.lastModified);
        //console.log(JSON.stringify(arguments));
        console.log("ajaxError:" + setting.url + " | readyState:" + xhr.readyState + " | status:" + xhr.status + " | statusText:" + xhr.statusText + " | error:" + error);
    });
    $(document).ajaxComplete(function () {
        console.log("[ajax document] ajaxComplete:" + this.lastModified);
    });
    $.ajaxSetup({
        timeout: 20000,
    });

    function ajaxStopAll() {
        for (var i in xhrArray) {
            if (xhrArray[i].readyState != 4)
                xhrArray[i].abort();
        }
        xhrArray = [];
    };

    function gotoFirst(model) {
        ajaxStopAll();
        model = model || {};
        common.popup.show($.extend(model, {
            callback: function () {
                location.href = common.firstPage;
                location.reload();
            }
        }));
    };

    var ajaxHandler = {
        async: true,
        contentType: "application/JSON",
        timeout: 2000,
        dataType: "json",
        url: "",
        retryTimer: null,
        retryCount: 0,
        retryLimit: 3,
        retryClick: false,
        beforeSend: function (xhr) {
            console.log("[ajax] beforeSend:" + this.url);
        },
        dataFilter: function (data, dataType) {
            // console.log("[ajax] dataFilter:" + dataType);
            // data = data.replace("\\r|\\n/g", "");

            /*data = {
                user: {
                    name: "dsfdff" + getRandom(1, 2),
                    age: getRandom(4, 80)
                }
            };
            return JSON.stringify(data);*/
            return data;
        },
        success: function (result, status, xhr) {
            var res = result || JSON.parse(xhr.responseText);
            console.log("[ajax] success ", arguments);
            var me = this;
            res = $.extend({
                resultCode: "success",
                serverTime: Date.now()
            }, res);

            //服务器的成功返回的警告或错误信息
            if (res.resultCode == "error") {
                gotoFirst({
                    title: me.url,
                    content: xhr.responseText || xhr.statusText,
                    callback: me.callback
                });
                return;
            }
            common.fetchModel(res, this.url);
            if (me.callback) {
                me.callback(res);
            }
        },
        error: function (xhr, status, error) {
            console.log("[ajax] error ", arguments);
            accessBusyCallback(this, xhr);
        },
        complete: function (xhr, status) {
            console.log("[ajax] complete:" + this.type);
            xhrArray.splice($.inArray(this, xhrArray), 1);
        },
        // statusCode: {
        //     404: function() {
        //         alert( "page not found" );
        //     }
        // }
    };

    var xhrArray = [];
    var baseUrl = ["/", "http://www.baidu.com/"];
    $.ajax = (function (base) {
        return function (obj) {
            console.log("reset define $.ajax");
            var xhr = $.extend({}, ajaxHandler, obj);
            if (xhr.retryCount == 0) {
                xhr.uri = xhr.url;
            } else {
                xhr.url = xhr.uri;
            }

            var ajax = base.call(window, xhr);
            xhrArray.push(ajax);
            return ajax;
        }
    })($.ajax)

    var that = {
        fetch: function () {

        },
        apiUrl: function (uri) {
            return window.isLocalJson ? "/json/" + uri + ".json" : uri;
        },
        get: function (uri, params, callback) {
            params["t"] = Date.now();
            $.ajax({
                callback: callback,
                type: "get",
                url: this.apiUrl(uri),
                data: $.param(params)
            });
        },
        post: function (uri, params, callback) {
            $.ajax({
                callback: callback,
                type: "post",
                url: this.apiUrl(uri),
                data: JSON.stringify(params),
            });
        },
        //model过滤
        pageFetch: function (page) {
            var queryList = [];
            _.each(page.needMode, function (value, name) {
                if (name in common.localModel) {
                    if (value == true) {
                        queryList.push(name);
                    }
                } else {
                    queryList.push(name);
                }
            });
            return queryList.length == 0 ? "" : (queryList.join(","));
        },
        pageUrl: function (page) {
            return window.isLocalJson ? "/json/" + page.name + ".json" : page.name;
        },
        pageGet: function (page, callback) {
            var url = this.pageUrl(page);
            $.ajax({
                callback: callback,
                type: "get",
                url: url,
                data: $.param({value: this.pageFetch(page)})
            });
        },
        pagePost: function (page, callback) {
            var url = this.pageUrl(page);
            $.ajax({
                callback: callback,
                type: "post",
                url: url,
                data: JSON.stringify({value: this.pageFetch(page)})
            });
        },
    };

    function accessBusyCallback(xhr, res) {
        if (res.responseText == "abort") {
            return;
        }
        var tips = $.extend({}, {
            title: "連線錯誤",
            content: "發生無法預期的錯誤。<br />很抱歉給您造成困擾。",
            gotoFirst: true,
        }, errorTips[res.status] || errorTips[-1], (errorTips[res.status] || errorTips[-1])[res.statusText] || {});

        tips.content = "[" + res.status + "][" + res.statusText + "]<br>" + tips.content;

        //自动重试
        if ("retryStandbyTime" in tips) {
            clearTimeout(xhr.retryTimer);
            xhr.retryTimer = null;
            if (xhr.retryCount <= xhr.retryLimit) {
                xhr.retryTimer = setTimeout(function () {
                    xhr.retryCount++;
                    $.ajax(xhr);
                }, tips.retryStandbyTime);
                return;
            }
        }

        //手动重试
        if (tips.retryClick == true && xhr.retryClick == false) {
            ajaxStopAll();
            common.popup.show($.extend(tips, {
                yes: "点击重试",
                callback: function () {
                    xhr.retryClick = true;
                    $.ajax(xhr);
                },
            }));
            return;
        }

        //最终显示
        if (tips.gotoFirst == true) {
            gotoFirst(tips);
        } else {
            ajaxStopAll();
            common.popup.show($.extend(tips, {yes: "关闭", callback: xhr.callback}));
        }
    };

    var errorTips = {
        "-1": {
            title: "錯誤",
            content: "請於連線狀態較佳的環境再次嘗試。",
            retryStandbyTime: 1000,
            "-1": {
                title: "錯誤",
                content: "發生無法預期的錯誤。<br />很抱歉給您造成困擾。",
                retryStandbyTime: 1000,
            }
        },
        0: {
            "timeout": {
                retryStandbyTime: 1000,
                title: "連線超時",
                content: "請於連線狀態較佳的環境再次嘗試。",
                retryClick: true
            },
            "error": {
                title: "",
                content: "請於連線狀態較佳的環境再次嘗試。",
                retryClick: true
            },
            content: "請於連線狀態較佳的環境再次嘗試。",
        },
        200: {
            "OK": {
                title: "解析出錯",
                content: "客戶端解析伺服器結果出錯。",
            },
            "error": {
                title: "出錯",
                content: "客戶端出錯。",
            },
        },
        404: {
            retryStandbyTime: 1000,
            content: "請於連線狀態較佳的環境再次嘗試。",
            gotoFirst: false,
        },
        429: {
            retryStandbyTime: 3000,
            content: "目前連線人數較多。<br>請稍待片刻再嘗試連線。",
            gotoFirst: false,
            retryClick: true
        },
        500: {
            retryStandbyTime: 3000,
        },
        502: {
            retryStandbyTime: 3000,
            content: "目前連線人數較多。<br>請稍待片刻再嘗試連線。",
            gotoFirst: false,
            retryClick: true
        },
        503: {
            retryStandbyTime: 1000,
            content: "請於連線狀態較佳的環境再次嘗試。",
        },
    }

    return that;
});